package corp.edu.amadeus.core.bluetooth.sender.broadcast;

import java.io.File;
import org.apache.log4j.Logger;
import corp.edu.amadeus.core.bluetooth.sender.helper.ContentSender;
import corp.edu.amadeus.core.bluetooth.management.DeviceManager;
import corp.edu.amadeus.core.bluetooth.wrapper.RemoteDeviceWrapper;
import corp.edu.amadeus.utils.file.FileUtils;
import corp.edu.amadeus.utils.log.LogTracer;

public class Broadcaster {

	private String content_path = null, content_name = null;

	private ContentSender sender = null;
	private static Logger log = Logger.getLogger(Broadcaster.class);
	private boolean sending = false;

	public Broadcaster(String ct_path, String ct_name) {
		this.content_path = ct_path + File.separator + ct_name;
		this.content_name = ct_name;
		this.sender = new ContentSender();
	}

	public boolean isSending() {
		return this.sending;
	}

	public void send() throws Exception {
		this.sending = true;
		log.debug("##### --- --- Sending process launched ......");
		try {
			byte[] content = FileUtils.extractFileContent(new File(
					this.content_path));
			for (RemoteDeviceWrapper remote_device : DeviceManager
					.getInstance().getRemoteDevices()) {
				log.debug("Sending content ( " + content.length + " bytes) to "
						+ remote_device.getFriendlyName() + "-"
						+ remote_device.getBtAddress());
				if (remote_device.isOBEXDevice()) {
					try {
						this.sender.sendContent(remote_device.getOBEXURL(),
								content, this.content_name);
					} catch (Exception e) {
						log.error("Problems sending content to "
								+ remote_device.getOBEXURL());
						LogTracer.printStackTraceError(e, log);
					}
				}
			}
		} catch (Exception e) {
			throw e;
		} finally {
			this.sending = false;
		}
	}

}